package com.fanyouzhao.ssm251.interceptor;

import com.fanyouzhao.ssm251.annotation.NeedsLog;
import com.fanyouzhao.ssm251.annotation.NeedsLogin;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @author: fanyouzhao
 * @date: 16:39 2021/6/22
 */
public class AuthInterceptor implements HandlerInterceptor {

    /**
     * 操作执行前拦截的操作
     *
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o                   方法对象
     * @return 是否拦截, true表示放行, false表示拦截
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        // 通过HandlerMethod类型获取参数o的方法特征，获取Method方法
        Method method = ((HandlerMethod) o).getMethod();
        Class<?> clazz = ((HandlerMethod) o).getBeanType();
        boolean annoFromMethod = method.isAnnotationPresent(NeedsLogin.class);
        boolean annoFromType = clazz.isAnnotationPresent(NeedsLogin.class);
        System.out.println("method:" + method);
        // 判断该方法有无NeedsLogin注解，有此注册就需要做权限判断
        if (annoFromMethod||annoFromType) {
            //权限判断
            System.out.println(method.getName() + "方法需要权限");
            return false;
        } else {
            return true;
        }
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
